package com.gzx.plugin.tjzy.modular.fm.controller;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.ServiceException;
import com.gzx.plugin.tjzy.modular.fm.dto.RingEventRequestDto;
import com.gzx.plugin.tjzy.modular.fm.dto.RingEventResponseDto;
import com.gzx.plugin.tjzy.modular.fm.service.FmService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RestController
@RequestMapping("/tjzy/outcall")
@Slf4j
public class FmController {

    private final FmService fmService;

    @PostMapping("/ring/event")
    public ResponseEntity<RingEventResponseDto> ringEvent(@RequestBody String json) {
        log.info("接收到振铃事件请求，原始参数: {}", json);

        // 1. 参数校验
        RingEventRequestDto ringEventRequestDto = parseAndValidateRequest(json);
        if (ringEventRequestDto == null) {
            return buildErrorResponse(HttpStatus.BAD_REQUEST, "请求参数非法");
        }

        try {
            // 2. 业务处理- 1、发送闪信；2、页面及耳机振铃提醒，后续开发
            fmService.sendFlashMessage(ringEventRequestDto);
            log.info("振铃事件处理成功，被叫号码: {}", ringEventRequestDto.getCalled());
            return ResponseEntity.ok(RingEventResponseDto.success());
        } catch (ServiceException e) {
            log.error("振铃事件业务处理失败:", e);
            return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }

    private RingEventRequestDto parseAndValidateRequest(String json) {
        try {
            RingEventRequestDto param = JSON.parseObject(json, RingEventRequestDto.class);
            if (param == null
                    || StringUtils.isBlank(param.getCalled())
                    || StringUtils.isBlank(param.getCaller())) {
                log.error("参数校验失败: called或caller为空");
                return null;
            }
            return param;
        } catch (Exception e) {
            log.error("JSON解析失败:", e);
            return null;
        }
    }

    private ResponseEntity<RingEventResponseDto> buildErrorResponse(HttpStatus status, String errorMsg) {
        RingEventResponseDto response = RingEventResponseDto.fail(String.valueOf(status.value()), errorMsg);
        return ResponseEntity.status(status).body(response);
    }
}
